const router = require('koa-router')();
const moment = require('moment');

router.prefix('/message');

// 获取互相关注的朋友
router.get('/getfriends', async (ctx, next) => {
  let { id } = ctx.request.query;
  // console.log(id)
  let sql = 'select fan.id sendId,user.id receiveId,username,image,fan.show,top from user,fan,attention where attention.id=fan.id and fan.fanId = attention.attentionId and fan.id=? and user.id = fan.fanId order by top desc'
  let result = await ctx.db.EXCUTE(sql, [id])
  // console.log(result)
  if (result.length != 0) {
    ctx.body = { code: 200, status: "success", list: result }
  } else {
    ctx.body = { code: 200, status: "暂无消息", list: [] }
  }
})

// 获取消息列表展示内容
router.get('/getlastmessage', async (ctx, next) => {
  let code;
  let status;
  let { id, receiveid } = ctx.request.query;
  // 查询最后一条消息
  let sql = 'select * from message where sendid = ? and receiveid = ? or sendid = ? and receiveid = ? order by time DESC';
  let result = await ctx.db.EXCUTE(sql, [id, receiveid, receiveid, id])
  // console.log(result)
  // 互发过消息找到最新一条消息 
  if (result.length != 0) {
    // console.log(result[0])
    let newtime = moment(result[0].time).format('YYYY/MM/DD HH:mm:ss');
    result[0].time = newtime;
    ctx.body = { code: code, status: status, last: result[0] }
  } else { // 没有互发消息，显示后关注对方的关注时间和默认语句
    let sql2 = 'select fan.id sendId,fan.fanId receiveId,fanTime,attentionTime from fan,attention where attention.id=fan.id and fan.fanId = attention.attentionId and fan.id=? and fan.fanId=?'
    let result = await ctx.db.EXCUTE(sql2, [id, receiveid])
    let newtime;
    // console.log(receiveid,result[0].fanTime,result[0].attentionTime)
    if (result[0].fanTime <= result[0].attentionTime) {
      newtime = moment(result[0].attentionTime).format('YYYY/MM/DD HH:mm:ss');
    } else {
      newtime = moment(result[0].fanTime).format('YYYY/MM/DD HH:mm:ss');
    }
    let obj = {
      content: '已经互相关注,快来聊天吧！',
      time: newtime,
    }
    ctx.body = { code: 200, status: "暂无聊天", last: obj }
  }
})

// 获取接收者的信息
router.get('/getreceiveid', async (ctx, next) => {
  let { receiveid } = ctx.request.query;
  let sql = 'select * from user where id=?'
  let result = await ctx.db.EXCUTE(sql, [receiveid])
  console.log(result)
  ctx.body = { code: 200, status: "success", user: result[0] }
})

// 获取所有消息(自己sendid和对方receiveid)
router.get('/gettalks', async (ctx, next) => {
  let { receiveid, sendid } = ctx.request.query;
  console.log(receiveid, sendid)
  let sql = 'select * from message where sendid = ? and receiveid = ? or sendid = ? and receiveid = ? order by time';
  let result = await ctx.db.EXCUTE(sql, [sendid, receiveid, receiveid, sendid])
  ctx.body = { code: 200, status: 'success', list: result }
})

// 发送消息
router.post('/addmessage', async (ctx, next) => {
  let { messageobj } = ctx.request.body
  let newtime = moment(messageobj.time).format('YYYY/MM/DD HH:mm:ss');
  let code;
  let status;
  let sql = 'insert into message(sendid,receiveid,content,time,stranger) values(?,?,?,?,?)'
  try {
    let result = await ctx.db.EXCUTE(sql, [messageobj.sendid, messageobj.receiveid, messageobj.content, newtime, messageobj.stranger])
    console.log(result.affectedRows)
    status = result.affectedRows === 1 ?
      '发送成功' : '发送失败 ';
    code = result.affectedRows === 1 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '发送失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 查找聊天记录
router.get('/searchchat', async (ctx, next) => {
  let { id1, id2, condition } = ctx.request.query;
  console.log(id1, id2, condition)
  if (condition == '') {
    ctx.body = { code: 200, status: 'success', list: [] }
  } else {
    let sql = `select * from message where (sendid = '${id1}' and receiveid = '${id2}' and content like '%${condition}%') or (sendid = '${id2}' and receiveid = '${id1}' and content like '%${condition}%') order by time DESC`;
    let result = await ctx.db.EXCUTE(sql)
    ctx.body = { code: 200, status: 'success', list: result }
  }
})

// 置顶
router.get('/gettop', async (ctx, next) => {
  let { id, receiveid } = ctx.request.query;
  console.log(id, receiveid)
  let code;
  let status;
  let sql = 'update fan set top = ? where id=? and fanId=?'
  try {
    let result = await ctx.db.EXCUTE(sql, [1, id, receiveid])
    console.log(result.affectedRows)
    status = result.affectedRows === 1 ?
      '置顶成功' : '置顶失败 ';
    code = result.affectedRows === 1 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '置顶失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 取消置顶
router.get('/getuntop', async (ctx, next) => {
  let { id, receiveid } = ctx.request.query;
  console.log(id, receiveid)
  let code;
  let status;
  let sql = 'update fan set top = ? where id=? and fanId=?'
  try {
    let result = await ctx.db.EXCUTE(sql, [0, id, receiveid])
    console.log(result.affectedRows)
    status = result.affectedRows === 1 ?
      '取消成功' : '取消失败 ';
    code = result.affectedRows === 1 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '取消失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 删除对话
router.get('/delete', async (ctx, next) => {
  let { id, receiveid } = ctx.request.query;
  console.log(id, receiveid)
  let code;
  let status;
  let sql = 'update fan set fan.show = ? where id=? and fanId=?'
  try {
    let result = await ctx.db.EXCUTE(sql, [1, id, receiveid])
    console.log(result.affectedRows)
    status = result.affectedRows === 1 ?
      '删除成功' : '删除失败 ';
    code = result.affectedRows === 1 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '删除失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 恢复对话框,点击私信,发起这个请求
router.get('/undelete', async (ctx, next) => {
  let { id, receiveid } = ctx.request.query;
  console.log(id, receiveid)
  let code;
  let status;
  let sql = 'update fan set fan.show = ? where id=? and fanId=?'
  try {
    let result = await ctx.db.EXCUTE(sql, [0, id, receiveid])
    console.log(result.affectedRows)
    status = result.affectedRows === 1 ?
      '恢复成功' : '恢复失败 ';
    code = result.affectedRows === 1 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '恢复失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 清空列表
router.get('/deleteall', async (ctx, next) => {
  let { id } = ctx.request.query;
  console.log(id)
  let code = 200;
  let status = 'success';
  let sql = 'update fan set fan.show = ? where id=?'
  try {
    let result = await ctx.db.EXCUTE(sql, [1, id])
    console.log(result.affectedRows)
    status = result.affectedRows != 0 ?
      '清空成功' : '清空失败 ';
    code = result.affectedRows != 0 ?
      200 : 400;
  } catch (e) {
    code = 400;
    status = '清空失败';
    console.log(e)
  }
  ctx.body = { code: code, status: status }
})

// 清空聊天记录
router.get('/clearchat', async (ctx, next) => {
  let { id, receiveid } = ctx.request.query;
  let code;
  let status;
  console.log(id, receiveid)
  let sqlCount = 'select count(id) as count from message where (sendid=? and receiveid=?) || (sendid=? and receiveid=?);';
  let result = await ctx.db.EXCUTE(sqlCount, [id, receiveid, receiveid, id])
  let count = result[0].count;
  console.log(count)
  if (count != 0) {
    let delsql = 'delete from message where (sendid=? and receiveid=?) || (sendid=? and receiveid=?)';
    try {
      let result = await ctx.db.EXCUTE(delsql, [id, receiveid, receiveid, id])
      console.log(result.affectedRows)
      status = result.affectedRows != 0 ? '清空成功' : '清空失败';
      code = result.affectedRows != 0 ? 200 : 401;
    } catch (e) {
      code = 402;
      status = '清空失败';
    }
  } else {
    code = 200;
    status = '清空成功'
  }
  ctx.body = { code: code, status: status }
})

module.exports = router;


// // 添加到数据库
// for (let item of result){
//     let sql2 = 'insert into friends(sendId,receiveId,receiveName,image) values(?,?,?,?)'
//     try{
//         let result = await ctx.db.EXCUTE(sql2,[item.sendId,item.recevieId,item.username,item.image])
//         console.log(result.affectedRows)
//         status = result.affectedRows === 1 ?
//           '增加成功':'增加失败 ';
//         code = result.affectedRows === 1 ?
//           200:400;
//       }catch(e){
//         code = 400;
//         status = '增加失败';
//         console.log(e)
//       }
// }

// //插入数据库中friends表格
// let sql2 = 'insert into friend(lasttime,lastcontent) values(?,?) where sendId = ? and recevieId = ?'
// try{
//     let result = await ctx.db.EXCUTE(sql2,[result[0].time,result[0].content,id,recevieid])
//     console.log(result.affectedRows)
//     status = result.affectedRows === 1 ?
//         '增加成功':'增加失败 ';
//     code = result.affectedRows === 1 ?
//         200:400;
//     }catch(e){
//     code = 400;
//     status = '增加失败';
//     console.log(e)
// } 